Creating a collapsible "Year > Month" tree structure is a great way to organize a blog as it grows. To do this, we'll use 11ty's JavaScript Data Files to group the posts and the HTML tags to handle the "collapsible" part without needing complex JavaScript.
1. Create the Grouping Logic
We need to tell 11ty how to group posts by year and month. Create a folder named _data (if you don't have one) and create a file inside called archives.js.
File: _data/archives.js
JavaScript
module.exports = (data) => {
const posts = data.collections.post || [];
const structure = {};
posts.forEach(post => {
const year = post.date.getFullYear();
const month = post.date.toLocaleString('default', { month: 'long' });
if (!structure[year]) structure[year] = {};
if (!structure[year][month]) structure[year][month] = [];
structure[year][month].push(post);
});
return structure;
};
---
2. Update the Sidebar in the Layout
Now, we’ll change the sidebar in _includes/layout.njk to loop through this new archives object. We will use the native HTML tags:
-
: Creates the collapsible container.
-
: Creates the clickable heading.
Update your
HTML
(Note: I added open to the Year so the current year is visible by default, but you can remove it if you want everything closed.)
---
3. Add a touch of CSS
To make the tree look cleaner, add this to your